package com.itheima.appserver.interceptor;

import com.itheima.model.domain.User;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户token
        String token = request.getHeader("Authorization");
        //判断用户token是否合法
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken) {
            //token不可用，返回401，拦截请求
            response.setStatus(401);
            return false;
        }
        //解析用户token
        Claims claims = JwtUtils.getClaims(token);
        String mobile = (String) claims.get("mobile");
        Integer id = (Integer) claims.get("id");
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);

        UserHandler.set(user);
        //token可用，放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHandler.remove();
    }
}
